#coding=utf-8
#
# Copyright (C) 2014  NianNian TECH Co., Ltd. All rights reserved.
# Created on May 12, 2014, by Junn
#
from auth.models import send_sms
from utils import eggs, logs, http
from core.views import CustomAPIView
from utils.http import JResponse
from core import codes
from core.push import push_to_single, push_to_all, push_to_many
from families.models import Family
from posts.models import Post
from core.decorators import login_required, login_required_mtd,\
    login_required_pro
from rest_framework.decorators import api_view
from settings.base import SMS_TEXT
import settings
import urllib
import httplib
from messages.models import PushMessage
from StringIO import StringIO
import Image
import requests
from core.serializers import serialize_response
import urllib2
from django.core.files.uploadedfile import SimpleUploadedFile,\
    InMemoryUploadedFile


mobile = '15982249075'
text = SMS_TEXT.get('signup')

class SMSView(CustomAPIView):
    
    def post(self, req):
        code = eggs.random_num()
        try:
            success, res = send_sms(mobile, text.format(code))
            if success: #短信发送成功
                return http.ok()
            return http.failed(res)
        except Exception, e:
            logs.error('send_sms error: %s' % e)
            return http.failed()
 
def test_jpush(req):
    #push.audience = jpush.audience(jpush.alias("30", "36"))
    #push.notification = jpush.notification(alert="Test: welcome to niannian !")
    #push.send()
    
    to = req.REQUEST.get('to', '')
    
    if to == 'one':
        msg = PushMessage('T', u'Test: 你有新问候', extras={'name': 'Junn', })
        try:
            push_to_single('27', msg)
            return http.ok()
        except Exception, e:
            logs.error('%s' % e) 
            return http.failed()   
    
    elif not to or to == 'all':
        msg = u'This is a system message'
        push_to_all(msg)
        return http.ok({'desc': 'message pushed successfully'})
    else:
        push_to_many(msg)
    
def test_unread_posts(req):
    #data = Post.objects.get_all_posts_unread_count()
    return http.ok()

# "37": [{"unc": 8, "fid": 28}, {"unc": 2, "fid": 12}]
def test_jpush_posts(req):
    extras = {'upcs': [{"unc": 8, "fid": 28}, {"unc": 2, "fid": 12}]}
    #extras = {"unc": 8, "fid": 28}
    msg = PushMessage('P', u'new posts', extras=extras)
    try:
        push_to_single("30", msg)
        return http.ok(extras)
    except Exception, e:
        logs.error('%s' % e)
        return http.failed()
    
class TestView(CustomAPIView):

    @login_required_pro    
    def get(self, req): # test_request_auth
        print '-------------------------------------------->   request.user:', req.user 
        print '-------------------------------------------->   request.auth:', req.auth 
        return http.ok({'request.auth': req.auth})   
    
    @login_required_pro
    def post(self, req): #test post request for auth token
        print '-------------------------------------------->   request.user2:', req.user
        print '-------------------------------------------->   request.auth2:', req.auth
        u = req.user.id if req.user else req.user
        return http.ok({'user': u, 'auth': req.auth}) 
    
@api_view(['GET'])      # the @api_view decorator with function based views to use django-rest-framework
@login_required_mtd 
def test_request_auth(req):    
    if req.user.is_authenticated():
        print 'user logined'
    else:
        print 'user not logined'
            
    return http.ok({'request.user': req.user.username, 'request.auth': req.auth.key})  

#from qiniu import Auth
import qiniu

access_key = settings.QINIU['access_key']
secret_key = settings.QINIU['secret_key']

def test_qiniu_upload(req):
    bucket_name = 'dondon'
    
    filepath = 'apks/dondon-1.1.1.apk'
    file = req.FILES.get('file', 'null')
    
    q = qiniu.Auth(access_key, secret_key)
    token = q.upload_token(bucket_name, filepath)
    
    print 'file.size:', file.size
    print 'file.name:', file.name
    
    # file need to be 
    try:
        ret, info = qiniu.put_file(token, filepath, file.file.name, mime_type="application/octet-stream", check_crc=True)        
        print ret
        print info
        print type(info)
        assert info.status_code == 200
        assert ret.key == filepath
    except Exception, e:
        logs.error('%s' % e)  
        return http.failed('%s' % e)       

    return http.ok()

def test_send_request(req):
    send_url = '/api/v2/app/version/541a7131f880a6a814000087?token=xxxxxxxxx'
    response_str = http.send_request('fir.im', send_url)
    
    print 'type(response_str):', type(response_str)
    print eval(response_str).get('versionShort') 
    
    return http.ok(eval(response_str))

@api_view(['GET']) 
def test_load_weixin_pic(req):
    url = "http://wx.qlogo.cn/mmopen/xxxxxxxxxxxx/0"

    user = req.user
    user.avatar = user.save_pic(http.request_file(url))
    user.save()
    
    return serialize_response(user)
    
    


